<template>
 <!-- list 只有在可视范围内才会检查滚动位置触发onLoad -->
 <!-- immediate-check:是否在初始化时立即执行滚动位置检查；解决评论里回复评论数据重复问题 -->
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error="error"
    error-text="加载失败，点击重试"
    :immediate-check="false"
    @load="onLoad"
  >
    <CommentItem
    v-for="(item, index) in list"
    :key="index"
    :comment="item"
    @reply-click="$emit('reply-click',$event)"
    />
  </van-list>
</template>

<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item.vue'

export default {
  name: 'CommentList',
  components: {
    CommentItem
  },
  props: {
    source: {
      type: [String, Number, Object],
      required: true
    },

    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      // 自定义prop数据验证
      validator (value) {
        return ['a', 'c'].includes(value)
      },
      default: 'a'
    }
  },
  data () {
    return {
    // list: [],
      localList: this.list,
      loading: false,
      finished: false,
      offset: null, // 获取下一页数据的标记
      limit: 10, // 每页有几条评论数据
      error: false
    }
  },
  created () {
    // 手动初始化onLoad,不后有loading效果
    this.onLoad()
    // 手动开启loading效果
    this.loading = true
  },
  methods: {
    async onLoad () {
      // 获取文章的评论和获取评论的回复是同一接口；接口参数不一样
      // type --a：文章的评论，--c评论的回复
      // source --文章的评论：传递文章的ID; 评论的回复：传递评论的ID
      try {
        // 请求数据
        const { data } = await getComments({
          type: this.type,
          source: this.source.toString(),
          offset: this.offset,
          limit: this.limit
        })
        // 将数据添加到列表
        // console.log(data)
        const { results } = data.data
        this.localList.push(...results)

        // 把文章评论总数量传给外部
        this.$emit('onload-success', data.data)
        // 将loading设置为false
        this.loading = false
        // 判断是否还有数据
        if (results.length) {
          this.offset = data.data.last_id
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less">
</style>
